<?php
class Daftar extends CI_Controller {

	function __construct()
	{
		parent::__construct();	
		$this->load->helper('flexigrid');
		$this->load->library('flexigrid');
		$this->load->library('form_validation');		
		$this->load->model('dpb_model');	
	}
	
	function index()
	{
		//ver lib
		
		/*
		 * 0 - display name
		 * 1 - width
		 * 2 - sortable
		 * 3 - align
		 * 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.)
		 */
		$colModel['no'] = array('No',40,TRUE,'center',0);
		$colModel['ubah'] = array('Edit',50,FALSE,'center',0);
		$colModel['detail'] = array('Detail',50,FALSE,'center',0);
		$colModel['TAHUN'] = array('Tahun',50,TRUE,'center',2);
		$colModel['NAMA_PEMOHON'] = array('Nama Pemohon',100,TRUE,'center',1);
		$colModel['ALAMAT_PEMOHON'] = array('Alamat',150,FALSE,'center',1);
		$colModel['TGL_PERMOHONAN'] = array('Tanggal Permohonan',100,TRUE,'center',1);
		$colModel['TGL_IJIN'] = array('Tanggal Perijinan',100,TRUE,'center',1);
		$colModel['NO_IJIN'] = array('No Ijin',100,FALSE,'center',1);
		$colModel['LOKASI'] = array('Lokasi',100,TRUE,'center',2);
		$colModel['KECAMATAN'] = array('Kecamatan',100,TRUE,'center',2);
		$colModel['KELURAHAN'] = array('Kelurahan',100,TRUE,'center',2);
		$colModel['TINGGI_AIR'] = array('Tinggi Air Maksimal (m)',150,FALSE,'center',0);
		$colModel['TITIK_TETAP'] = array('Titik Tetap',150,FALSE,'center',1);
		
		
		/*
		 * Aditional Parameters
		 */
		$gridParams = array(
		'width' => 'auto',
		'height' => '355',
		'rp' => 15,
		'rpOptions' => '[10,15,20,25,40]',
		'pagestat' => 'Displaying: {from} to {to} of {total} items.',
		'blockOpacity' => 0.5,
		'title' => 'Daftar Keseluruhan Data Peil Banjir'
		);
		
		/*
		 * 0 - display name
		 * 1 - bclass
		 * 2 - onpress
		 */
		$buttons[] = array('Tambah','add','dpb_js');
		$buttons[] = array('Hapus','delete','dpb_js');
		$buttons[] = array('separator');
		$buttons[] = array('Pilih Semua','add','dpb_js');
		$buttons[] = array('Deselect All','delete','dpb_js');
		$buttons[] = array('separator');
        $buttons[] = array('Cetak Data','print','dpb_js');
        $buttons[] = array('separator');

		
		//Build js
		//View helpers/flexigrid_helper.php for more information about the params on this function
		$grid_js = build_grid_js('flex1',site_url("dpb/daftar/daftar_grid"),$colModel,'no','asc',$gridParams,$buttons);
		
		$data['title'] = "Contoh Flexigrid";
		$data['info'] = "Flexigrid";
		$data['js_grid'] = $grid_js;
		$data['version'] = "0.36";
		$data['download_file'] = "Flexigrid_CI_v0.36.rar";
		
		$data['added_js'] = 
			"<script type='text/javascript'>
			function dpb_js(com,grid)
			{
				if (com=='Pilih Semua')
				{
					$('.bDiv tbody tr',grid).addClass('trSelected');
				}
				
				if (com=='Batal Memilih Semua')
				{
					$('.bDiv tbody tr',grid).removeClass('trSelected');
				}
				
				if (com=='Cetak Data')
                {
                    location.href='".base_url()."index.php/dpb/cetak/'; 
                }

				if (com=='Tambah')
				{
					location.href='".base_url()."index.php/dpb/daftar/input_dpb'; 
				}
				
				if (com=='Hapus')
				{
				   if($('.trSelected',grid).length>0){
					   if(confirm('Anda yakin ingin menghapus ' + $('.trSelected',grid).length + ' buah data?')){
							var items = $('.trSelected',grid);
							var itemlist ='';
							for(i=0;i<items.length;i++){
								itemlist+= items[i].id.substr(3)+',';
							}
							$.ajax({
							   type: 'POST',
							   url: '".site_url('/dpb/daftar/delete_dpb')."',
							   data: 'items='+itemlist,
							   success: function(data){
								$('#flex1').flexReload();
								alert(data);
							   }
							});
						}
					} else {
						return false;
					} 
				}          
			} 
			</script>
			";
		
		/* $data['notification'] = "";
		if($this->session->userdata('notification')!=''){
			$data['notification'] = "
				<script>
					$(document).ready(function() {
						$.growlUI('Pesan :', '".$this->session->userdata('notification')."'); 
					});
				</script>
			";
		}//end if */	
		
		$data['content'] = $this->load->view('grid',$data,true);
		$this->load->view('main',$data);
		//$this->load->view('grid',$data);
		//$this->load->view('flexigrid',$data);
	}
	
	function daftar_grid()
	{
	
		//List of all fields that can be sortable. This is Optional.
		//This prevents that a user sorts by a column that we dont want him to access, or that doesnt exist, preventing errors.
		$valid_fields = array('IDPEIL_BANJIR','TAHUN','NAMA_PEMOHON','TGL_IJIN','TGL_PERMOHONAN','LOKASI','KECAMATAN','KELURAHAN','TINGGI_AIR','TITIK_TETAP');
		
		$this->flexigrid->validate_post('IDPEIL_BANJIR','asc',$valid_fields);

		$records = $this->dpb_model->get_dpb_grid();
		
		$this->output->set_header($this->config->item('json_header'));
		$no = 1;
		/*
		 * Json build WITH json_encode. If you do not have this function please read
		 * http://flexigrid.eyeviewdesign.com/index.php/flexigrid/example#s3 to know how to use the alternative
		 */
		foreach ($records['records']->result() as $row)
		{
			$record_items[] = array($row->IDPEIL_BANJIR,
			$no,
			'<a href=\''.site_url().'/dpb/daftar/edit_dpb/'.$row->IDPEIL_BANJIR.'/\'><img border=\'0\' src=\''.base_url().'images/main/28.png\'></a> ',
			'<a href=\''.site_url().'/dpb/daftar/tampil/'.$row->IDPEIL_BANJIR.'/\' onclick="OpenPopup(this.href); return false"><img border=\'0\' src=\''.base_url().'images/main/77.png\'></a> ',
			$row->TAHUN,
			$row->NAMA_PEMOHON,
			$row->ALAMAT_PEMOHON,
			$row->TGL_PERMOHONAN,
			$row->TGL_IJIN,
			$row->NO_IJIN,
			$row->LOKASI,
			$row->KELURAHAN,
			$row->KECAMATAN,
			$row->TINGGI_AIR,
			$row->TITIK_TETAP
			);
			$no++;
		}
		//Print please
		if(isset($record_items))
				$this->output->set_output($this->flexigrid->json_build($records['record_count'],$record_items));
			else
				$this->output->set_output('{"page":"1","total":"0","rows":[]}');
	}
	
	function cek_validasi() {	
			// Setting Rules
			$this->form_validation->set_rules('tahun', 'Tahun', 'callback_cek_dropdown');
			$this->form_validation->set_rules('nama', 'Nama Pemohon', 'required');
			$this->form_validation->set_rules('alamat', 'Alamat Pemohon', 'required');
			$this->form_validation->set_rules('tgl_perijinan', 'Tanggal Perijinan', 'required');
			$this->form_validation->set_rules('tgl_permohonan', 'Tanggal Permohonan', 'required');
			$this->form_validation->set_rules('lokasi', 'Lokasi', 'required');
			$this->form_validation->set_rules('kecamatan', 'Kecamatan', 'callback_cek_dropdown');
			$this->form_validation->set_rules('kelurahan', 'Kelurahan', 'callback_cek_dropdown');
			$this->form_validation->set_rules('tinggi_air', 'Tinggi Air', 'required');
			$this->form_validation->set_rules('titik_tetap', 'Titik Tetap', 'required');
			
			// Setting Error Message
			$this->form_validation->set_message('required', 'Kolom %s harus diisi!!');
			
			// Setting Delimiter
			$this->form_validation->set_error_delimiters('<li class="error">', '</li>');
			return $this->form_validation->run();
			
	}
	
	
	
	function cek_validasi_edit() {	
			// Setting Rules
			$this->form_validation->set_rules('tahun', 'Tahun', 'callback_cek_dropdown|callback_cek_data_edit');
			$this->form_validation->set_rules('nama', 'Nama Pemohon', 'required');
			$this->form_validation->set_rules('alamat', 'Alamat Pemohon', 'required');
			$this->form_validation->set_rules('tgl_perijinan', 'Tanggal Perijinan', 'required');
			$this->form_validation->set_rules('no_ijin', 'No Ijin', 'required');
			$this->form_validation->set_rules('tgl_permohonan', 'Tanggal Permohonan', 'required');
			$this->form_validation->set_rules('lokasi', 'Lokasi', 'required');
			$this->form_validation->set_rules('kecamatan', 'Kecamatan', 'callback_cek_dropdown');
			$this->form_validation->set_rules('kelurahan', 'Kelurahan', 'callback_cek_dropdown');
			$this->form_validation->set_rules('tinggi_air', 'Tinggi Air', 'required');
			$this->form_validation->set_rules('titik_tetap', 'Titik Tetap', 'required');
			
			// Setting Error Message
			$this->form_validation->set_message('required', 'Kolom %s harus diisi!!');
			
			// Setting Delimiter
			$this->form_validation->set_error_delimiters('<li class="error">', '</li>');
			return $this->form_validation->run();
			
	}
	
	function input_dpb()
    {
		$kecamatan = $this->dpb_model->get_all_kecamatan();
				
 		if ($this->cek_validasi() == FALSE){
				
				$kecamatan_options[''] = '-- Pilih Kecamatan --';
					foreach($kecamatan->result() as $kcm){
					$kecamatan_options[$kcm->IDKECAMATAN] = $kcm->NAMA_KECAMATAN;
					}
				
				$kelurahan_options[''] = '-- Pilih Kelurahan --';
				if(isset($_POST['kecamatan'])){
				$kelurahan = $this->dpb_model->get_klr_by_kcm($this->input->post('kecamatan'));
					foreach($kelurahan->result() as $klr){
						$kelurahan_options[$klr->NAMA_KELURAHAN] = $klr->NAMA_KELURAHAN;
					}
				}
				
				$data['kecamatan_options'] = $kecamatan_options;
				$data['kelurahan_options'] = $kelurahan_options;
				$data['status'] = 'new';
				$data['content'] = $this->load->view('dpb/form_dpb',$data,true);
				$this->load->view('main',$data);
			}
			else{
				$this->insert_dpb();
			}            
    }
	
	function insert_dpb(){
		$get_kecamatan = $this->dpb_model->get_kecamatanID($this->input->post('kecamatan'));
		foreach($get_kecamatan->result() as $row){
				$nama_kecamatan = $row->NAMA_KECAMATAN;
			}

		$cek_foto_lokasi = $_FILES['foto_lokasi']['name'];
			if($cek_foto_lokasi != ""){
				
				if(!is_dir('./uploads/dpb')){
					mkdir('./uploads/dpb',0777);
				}
				
				// Upload Foto
				$config['upload_path'] = './uploads/dpb/';
				$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp';
				$config['max_size']	= '2000';
				$config['encrypt_name']	= TRUE;
				
				$this->load->library('upload', $config);
				
				if(!$this->upload->do_upload('foto_lokasi')){
					$this->session->set_userdata('foto_lokasi', $this->upload->display_errors("<p>Error Foto : ", "</p>"));
					$data_file_lokasi = NULL;
					$valid_file = FALSE;
				}else{
					$data_file_lokasi = $this->upload->data();
					$valid_file = TRUE;
				}
				
				$file_foto_lokasi = $data_file_lokasi['file_name'];
			}else{
				$file_foto_lokasi = NULL;
				$valid_file = TRUE;
			}
			
		$cek_foto_sketsa = $_FILES['foto_sketsa']['name'];
			if($cek_foto_sketsa != ""){
				
				if(!is_dir('./uploads/dpb')){
					mkdir('./uploads/dpb',0777);
				}
				
				// Upload Foto
				$config['upload_path'] = './uploads/dpb/';
				$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp';
				$config['max_size']	= '2000';
				$config['encrypt_name']	= TRUE;
				
				$this->load->library('upload', $config);
				
				if(!$this->upload->do_upload('foto_sketsa')){
					$this->session->set_userdata('foto_sketsa', $this->upload->display_errors("<p>Error Foto : ", "</p>"));
					$data_file_sketsa = NULL;
					$valid_file = FALSE;
				}else{
					$data_file_sketsa = $this->upload->data();
					$valid_file = TRUE;
				}
				
				$file_foto_sketsa = $data_file_sketsa['file_name'];
			}else{
				$file_foto_sketsa = NULL;
				$valid_file = TRUE;
			}

		$data = array(
			'TAHUN' 				=> $this->input->post('tahun'),
			'NAMA_PEMOHON' 			=> $this->input->post('nama'),
			'ALAMAT_PEMOHON' 		=> $this->input->post('alamat'),
			'TGL_IJIN' 				=> $this->input->post('tgl_perijinan'),
			'NO_IJIN' 				=> $this->input->post('no_ijin'),
			'TGL_PERMOHONAN' 		=> $this->input->post('tgl_permohonan'),
			'LOKASI' 				=> $this->input->post('lokasi'),
			'KECAMATAN' 			=> $nama_kecamatan,
			'KELURAHAN' 			=> $this->input->post('kelurahan'),
			'TINGGI_AIR' 			=> $this->input->post('tinggi_air'),
			'TITIK_TETAP'			=> $this->input->post('titik_tetap'),
			'UPLOAD_PATH_1' 		=> $file_foto_lokasi,
			'UPLOAD_PATH_2' 		=> $file_foto_sketsa,
			'STATUS' 				=> 1			
		);
		
		$this->dpb_model->add_dpb($data);
		redirect('dpb/daftar'); 
	}
	
	function edit_dpb($id_dpb)
    {
		$this->session->set_userdata('id_dpb',$id_dpb);
 		$kecamatan = $this->dpb_model->get_all_kecamatan();
 		$dpb = $this->dpb_model->get_id_dpb($id_dpb);
				
 		if ($this->cek_validasi() == FALSE){
				
				$kecamatan_options['0'] = '-- Pilih Kecamatan --';
					foreach($kecamatan->result() as $kcm){
					$kecamatan_options[$kcm->IDKECAMATAN] = $kcm->NAMA_KECAMATAN;
					}
				
				$kelurahan_options['0'] = '-- Pilih Kelurahan --';
				if(isset($_POST['kecamatan'])){
				$kelurahan = $this->dpb_model->get_klr_by_kcm($this->input->post('kecamatan'));
					foreach($kelurahan->result() as $klr){
						$kelurahan_options[$klr->NAMA_KELURAHAN] = $klr->NAMA_KELURAHAN;
					}
				}

				foreach($dpb->result() as $row){
					$data['idpeil_banjir'] = $row->IDPEIL_BANJIR;
					$data['tahun'] = $row->TAHUN;
		            $data['nama']  = $row->NAMA_PEMOHON;
		            $data['alamat'] = $row->ALAMAT_PEMOHON;
		            $data['no_ijin'] = $row->NO_IJIN;
		            $data['tgl_perijinan'] = $row->TGL_IJIN;
		            $data['tgl_permohonan'] = $row->TGL_PERMOHONAN;
		            $data['lokasi'] = $row->LOKASI;
		            $data['kelurahan'] = $row->KELURAHAN;
		            $data['kecamatan'] = $row->KECAMATAN;
		            $data['tinggi_air'] = $row->TINGGI_AIR;
		            $data['titik_tetap'] = $row->TITIK_TETAP;
		            $data['foto_lokasi'] = $row->UPLOAD_PATH_1;
		            $data['foto_sketsa'] = $row->UPLOAD_PATH_2;
				}
				
				$data['kecamatan_options'] = $kecamatan_options;
				$data['kelurahan_options'] = $kelurahan_options;
				$data['status'] = 'edit';
				$data['content'] = $this->load->view('dpb/form_edit_dpb',$data,true);
				$this->load->view('main',$data);
			}
			else{
				$this->update_dpb($id_dpb);
			}            
    }
	
	function update_dpb($id_dpb){
		$get_kecamatan = $this->dpb_model->get_kecamatanID($this->input->post('kecamatan'));
		foreach($get_kecamatan->result() as $row){
				$nama_kecamatan = $row->NAMA_KECAMATAN;
			}

		$cek_foto_lokasi = $_FILES['foto_lks']['name'];
			if($cek_foto_lokasi != ""){
				
				if(!is_dir('./uploads/dpb')){
					mkdir('./uploads/dpb',0777);
				}
				
				// Upload Foto
				$config['upload_path'] = './uploads/dpb/';
				$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp';
				$config['max_size']	= '2000';
				$config['encrypt_name']	= TRUE;
				
				$this->load->library('upload', $config);
				
				if(!$this->upload->do_upload('foto_lks')){
					$data_file_lokasi = NULL;
					$valid_file = FALSE;
				}else{
					$data_file_lokasi = $this->upload->data();
					$valid_file = TRUE;
				}
				
				$file_foto_lokasi = $data_file_lokasi['file_name'];
			}else{
				$file_foto_lokasi = NULL;
				$valid_file = TRUE;
			}
			
		$cek_foto_sketsa = $_FILES['foto_sks']['name'];
			if($cek_foto_sketsa != ""){
				
				if(!is_dir('./uploads/dpb')){
					mkdir('./uploads/dpb',0777);
				}
				
				// Upload Foto
				$config['upload_path'] = './uploads/dpb/';
				$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp';
				$config['max_size']	= '2000';
				$config['encrypt_name']	= TRUE;
				
				$this->load->library('upload', $config);
				
				if(!$this->upload->do_upload('foto_sks')){
					$data_file_sketsa = NULL;
					$valid_file = FALSE;
				}else{
					$data_file_sketsa = $this->upload->data();
					$valid_file = TRUE;
				}
				
				$file_foto_sketsa = $data_file_sketsa['file_name'];
			}else{
				$file_foto_sketsa = NULL;
				$valid_file = TRUE;
			}

		$data = array(
			'TAHUN' 				=> $this->input->post('tahun'),
			'NAMA_PEMOHON' 			=> $this->input->post('nama'),
			'ALAMAT_PEMOHON' 		=> $this->input->post('alamat'),
			'TGL_IJIN' 				=> $this->input->post('tgl_perijinan'),
			'NO_IJIN' 				=> $this->input->post('no_ijin'),
			'TGL_PERMOHONAN' 		=> $this->input->post('tgl_permohonan'),
			'LOKASI' 				=> $this->input->post('lokasi'),
			'KECAMATAN' 			=> $nama_kecamatan,
			'KELURAHAN' 			=> $this->input->post('kelurahan'),
			'TINGGI_AIR' 			=> $this->input->post('tinggi_air'),
			'TITIK_TETAP'			=> $this->input->post('titik_tetap'),
			'UPLOAD_PATH_1'			=> $this->input->post('file_foto_lokasi'),
			'UPLOAD_PATH_2'			=> $this->input->post('file_foto_sketsa')
		);
		$this->dpb_model->edit_dpb($id_dpb,$data);
		redirect('dpb/daftar'); 
	}
	
	//Delete
	function delete_dpb()
	{
		$dpb_ids_post_array = explode(",",$this->input->post('items'));
		$msg = '';
		foreach($dpb_ids_post_array as $index => $id_dpb){
			if (isset($id_dpb) && $id_dpb != "") {
				$this->dpb_model->delete_dpb($id_dpb);
						
			
			$msg .= "Daftar Peil Banjir dengan id (".$id_dpb.") telah berhasil dihapus.\n";
			}
		}
		$this->output->set_header($this->config->item('ajax_header'));
		$this->output->set_output($msg);
	}
    
    //Print
    function cetak()
    {
        $data['dpb'] = $this->dpb_model->get_dpb();
        $header = '';
		header("Content-type: application/x-msdownload"); 
		header("Content-Disposition: attachment; filename=Rekap_dpb.xls"); 
		header("Pragma: no-cache"); 
		header("Expires: 0");
		echo $header;
				
		$this->load->view('rekap/cetak_dpb_all',$data);
    }
	
    function tampil($id_dpb)
	{
		$record_dpb = $this->dpb_model->get_id_dpb($id_dpb);
			foreach ($record_dpb->result() as $row){
                $data['tahun'] = $row->TAHUN;
				$data['nama'] = $row->NAMA_PEMOHON;
				$data['alamat'] = $row->ALAMAT_PEMOHON;
				
				$tgl1 = $row->TGL_IJIN;
				$data['tgl_perijinan'] = date("d-m-Y", strtotime($tgl1));
				$tgl2 = $row->TGL_PERMOHONAN;
				$data['tgl_permohonan'] = date("d-m-Y", strtotime($tgl2));
				
				$data['lokasi'] = $row->LOKASI;
				$data['no_ijin'] = $row->NO_IJIN;
				$data['kcm'] = $row->KECAMATAN;
				$data['klr'] = $row->KELURAHAN;

				$data['tinggi_air'] = $row->TINGGI_AIR;
				$data['titik_tetap'] = $row->TITIK_TETAP;

				$data['foto_1'] = $row->UPLOAD_PATH_1;
				$data['foto_2'] = $row->UPLOAD_PATH_2;
            }
		
		$this->load->view('dpb/detail_dpb',$data);
	}

	//cek_dropdown
	function cek_dropdown($value){
	$tahun= $this->input->post('tahun');
		if($tahun === '0'){
			$this->form_validation->set_message('cek_dropdown', 'Kolom %s harus diisi!!');
			return FALSE;
		}
		else{
			return TRUE;
		}
	}
 	
	function cek_data($value){
		$tahun= $this->input->post('tahun');

		$sql =  $this->db->query("SELECT COUNT(TAHUN) AS CEK FROM TAHUN WHERE TAHUN = '".$tahun."' AND STATUS = 1");
		
		$CEK='';
			
		foreach ($sql->result() as $rows){
			$CEK=$rows->CEK;
		}
		
		if($CEK==0){
				return TRUE;
		}else{
				$this->form_validation->set_message('cek_data', 'Data %s sudah diinisialisasikan!!!');
				return FALSE;
		}		
		
	}
  
	function cek_data_edit($value){
		$tahun= $this->input->post('tahun');
		
		$sql =  $this->db->query("SELECT COUNT(TAHUN) AS CEK FROM TAHUN WHERE TAHUN = '".$tahun."' AND STATUS = 1");
		$data = $this->tahun_model->get_tahunID($this->session->userdata('id_tahun'));
		
		
		$CEK='';
			
		foreach ($sql->result() as $rows){
			$CEK=$rows->CEK;
		}
		
		$tahun_lama='';
		foreach ($data->result() as $rows){
			$tahun_lama=$rows->TAHUN;
		}
		
		
		if($tahun == $tahun_lama)
		{
			return TRUE;
		}
		else{
			if($CEK==0){
					return TRUE;
			}else{
					$this->form_validation->set_message('cek_data_edit', 'Data %s sudah diinisialisasikan!!!');
					return FALSE;
			}		
		}
	}
  
}
?>